<script setup>
import { onMounted, ref } from "vue";
import luckysheet from "luckysheet";
import LuckyExcel from "luckyexcel";
import { useAnalysetStore } from "@/store/index";
import AnalyesAPI from "@/api/system/analyes";
import {
  filterValidSampleAdatas,
  removeNullSampleSN,
  processTableData,
  transformData,
  filterValidSamples,
  getHeaders,
  splitDataIntoPages,
} from "@/utils/method";
import dayjs from "dayjs";
import CapacityB from "@/components/analysisSheetComponents/ambientAir/tmpl75/index.vue";
// pdf内容
import indexPdf from "@/components/analysisSheetComponents/ambientAir/tmpl75/indexPdf.vue";
import router from "@/router/index";
import MyDevice from "@/components/analysisSheetComponents/component/MyDevice.vue";
import Index from "@/components/analysisSheetComponents/component/index.vue";

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: "zh",
  autoCalculate: true,
  data: [
    {
      column: 10, // 列数
      defaultRowHeight: 30, // 自定义行高
      defaultColWidth: 100, // 自定义列宽
      celldata: [
        // 初始化表格数据，第一行包含表头
        { r: 0, c: 0, v: "元素（模式）" }, // A1
        //第二行
        { r: 1, c: 0, v: "检出限()" }, // A1
        //第三行
        { r: 2, c: 0, v: "样品编号" }, // A1
        { r: 2, c: 1, v: "类型" }, // A1
        { r: 2, c: 2, v: "实际体积 标况体积 (m³)" }, // A1
        { r: 2, c: 3, v: "切割份数n" }, // A1
        { r: 2, c: 4, v: "定容体积V(mL)" }, // A1
        { r: 2, c: 5, v: "稀释倍数f" }, // A1
        { r: 2, c: 6, v: "φ(O₂)(%)" }, // A1
        { r: 2, c: 7, v: "机读浓度ρ-ρ₀(µg/L)" },
        { r: 2, c: 8, v: "监测浓度ρ₁(    )" },
        { r: 2, c: 9, v: "排放浓度ρ₂(    )" },
        { r: 2, c: 10, v: "测定结果" },
        { r: 2, c: 11, v: "机读浓度ρ-ρ₀( µg/L)" },
        { r: 2, c: 12, v: "监测浓度ρ₁()" },
        { r: 2, c: 13, v: "排放浓度ρ₂()" },
        { r: 2, c: 14, v: "测定结果" },
        { r: 2, c: 15, v: " 机读浓度ρ-ρ₀(µg/L)" },
        { r: 2, c: 16, v: " 监测浓度ρ₁(    )" },
        { r: 2, c: 17, v: " 排放浓度ρ₂(    )" },
        { r: 2, c: 18, v: " 测定结果" },
        { r: 2, c: 19, v: "机读浓度ρ-ρ₀(µg/L) " },
        { r: 2, c: 20, v: "监测浓度ρ₁(    ) " },
        { r: 2, c: 21, v: "排放浓度ρ₂(    ) " },
        { r: 2, c: 22, v: "测定结果 " },
        { r: 0, c: 23, v: "备注" },
      ], // 初始化数据
      config: {
        merge: {
          "0_0": {
            r: 0, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 7, // 跨越的列数
          },
          "1_0": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 7, // 跨越的列数
          },
          "0_7": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "1_7": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "0_11": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "1_11": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "0_15": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "1_15": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "0_19": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "1_19": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },

          "0_23": {
            r: 1, // 起始行
            c: 0, // 起始列
            rs: 3, // 跨越的行数
            cs: 1, // 跨越的列数
          },
        }, // 合并单元格
        rowlen: {}, // 表格行高
        columnlen: {
          // 设置列宽
          0: 100,
          1: 100,
          2: 100,
          3: 130,
          4: 130,
          5: 130,
          6: 130,
          7: 130,
          8: 130,
          9: 130,
        }, // 表格列宽
      },
    },
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const waterForm = ref({
  bdatas: {
    dcwName: [],
    jcx: [],
    // 溶液配置
    rypz: Array.from({ length: 4 }, () => ({
      bzzbyph: "",
      bzzbynd: "",
      zbyyxrq: "",
      bzsyynd: "",
      pzrq: "",
    })),
    // 标准曲线
    bzqx: {},
    // bzqx: [],
    ys: {},
    jcx_b: {},
    cdxx: {},
    cfxxz: {},
    jhd: {},
    kbycd_fx: {},
    pxycd_fx: {},
  },
  pxycd: [],
  jbycd: [],
  unit: {},
  // 复制粘贴
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  },
});
const switchAB = ref(true);
const sheetData = ref("");
const jsonData = ref(null);
const checkTime = ref("");
const processedData = ref([]);
const cdatas = ref([]);
const checkDialogVisible = ref(false);
const analyseStatusPage = useAnalysetStore();
const record_sn = analyseStatusPage.waterForm.record_sn;
const drawer2 = ref(false);
const sampleSnList = ref([]);
const switchAdd = ref(true);
// pdf显示隐藏
const showTargetPage = ref(false);
const tableHeaders = ref([]);
const tabler = ref([]);
// 以上是pdf
const listB = ref({
  kbyList: [],
  qxyList: [],
  pxyList: [],
  bzyList: [],
});
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取表单信息
  getWaterCapacity();
  // 复制粘贴
  getMethod();
});

// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number; //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
    ? analyseStatusPage.waterForm.tableItem.test_method
    : analyseStatusPage.waterForm.tableItem.test_method_number; //分析方法
  waterForm.value.category_id =
    analyseStatusPage.waterForm.tableItem.sample_category; // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates;
};

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  // console.log("");
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 25,
    record_sn: record_sn,
    // record_sn: 40,
  };

  AnalyesAPI.getAnalyseACapacity(josn).then((data) => {
    // console.log("获取水质容量 A单", data);
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data;
      sheetData.value = data.configs;
      options.data = sheetData.value;
      luckysheet.create(options);
      // bdatas
      waterForm.value.bdatas =
        Array.isArray(data.bdatas) && data.bdatas.length === 0
          ? {}
          : data.bdatas;
      // bzqx
      waterForm.value.bdatas.bzqx =
        Array.isArray(data.bdatas.bzqx) && data.bdatas.bzqx.length === 0
          ? {}
          : data.bdatas.bzqx;
      // unit
      waterForm.value.unit =
        Array.isArray(data.unit) && data.unit.length === 0 ? {} : data.unit;
      //  jcx
      waterForm.value.bdatas.jcx =
        Array.isArray(data.bdatas.jcx) && data.bdatas.jcx.length === 0
          ? {}
          : data.bdatas.jcx;
      // cdxx
      waterForm.value.bdatas.cdxx =
        Array.isArray(data.bdatas.cdxx) && data.bdatas.cdxx.length === 0
          ? {}
          : data.bdatas.cdxx;
      // cfxxz
      waterForm.value.bdatas.cfxxz =
        Array.isArray(data.bdatas.cfxxz) && data.bdatas.cfxxz.length === 0
          ? {}
          : data.bdatas.cfxxz;
      // jhd
      waterForm.value.bdatas.jhd =
        Array.isArray(data.bdatas.jhd) && data.bdatas.jhd.length === 0
          ? {}
          : data.bdatas.jhd;
      // kbycd_fx
      waterForm.value.bdatas.kbycd_fx =
        Array.isArray(data.bdatas.kbycd_fx) && data.bdatas.kbycd_fx.length === 0
          ? {}
          : data.bdatas.kbycd_fx;
      // pxycd_fx
      waterForm.value.bdatas.pxycd_fx =
        Array.isArray(data.bdatas.pxycd_fx) && data.bdatas.pxycd_fx.length === 0
          ? {}
          : data.bdatas.pxycd_fx;
      processedData.value = data.adatas;
      // ys
      waterForm.value.bdatas.ys =
        Array.isArray(data.bdatas.ys) && data.bdatas.ys.length === 0
          ? {}
          : data.bdatas.ys;
      processedData.value = data.adatas;
      //处理adata到pdf
      tableHeaders.value = splitDataIntoPages(data.adatas, 88);
      tabler.value = getHeaders(data.adatas, 23);
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      };
    }
  });
};

// 保存新增表单
const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON

  const data = options.data[0].data.map((row) => {
    return row
      .map((cell) => {
        return cell
          ? {
              field: cell.m || "默认字段",
              // field: cell.m || null,
              value: cell.v || null,
            }
          : null;
      })
      .filter((cell) => cell !== null); // 删除 null 值
  });

  processedData.value = filterValidSampleAdatas(processDate(data));

  cdatas.value = filterValidSamples(transformData(processedData.value));
  // console.log(cdatas.value);
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status;
    delete waterForm.value.reviewer_id;
  }
  // console.log(waterForm.value, "device");
  // //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value,
  }).then((data) => {
    // console.log("调接口拿数据", data);
    ElMessage.success("保存成功");
    getWaterCapacity();
    switchAdd.value = false;
  });
};

// 剔除样品浓度ω( )
const extractBracketContent = (text) => {
  const match = text.match(/\((.*?)\)/);
  return match ? match[1] : text; // 如果匹配成功，返回括号内的内容，否则返回原文本
};
const processDate = (data) => {
  if (!data || data.length < 3) {
    return [];
  }
  // 提取表头信息
  const header1 = data[0]
    .map((item) => item.value)
    .filter((value) => value !== null);
  console.log(header1);
  const header2 = data[1]
    .map((item) => item.value)
    .filter((value) => value !== null);
  const header3 = data[2]
    .map((item) => item.value)
    .filter((value) => value !== null);

  //
  waterForm.value.bdatas.dcwName.push(...header1.slice(1, 6));
  // waterForm.value.bdatas.jcx.push(...header2.slice(1, 6));
  // 提取数据行
  // const row = data[2].map(item => item.value);
  const rows = data
    .slice(3)
    .map((rowData) => rowData.map((item) => item.value));

  // 构建嵌套结构
  // 构建嵌套结构
  return rows.map((row) => {
    const result = header3.slice(0, 22).reduce((acc, key, index) => {
      acc[key] = row[index];
      return acc;
    }, {});
    result[header1[5]] = row[22]; // 额外的字段
    return result;
  });
};

// 确认提交校核
const handleSubmit = () => {
  const formattedDate = checkTime.value
    ? dayjs(checkTime.value).format("YYYY-MM-DD")
    : "";
  // console.log(analyseStatusPage.waterForm.id);
  AnalyesAPI.handleCheckTimeData({
    id: analyseStatusPage.waterForm.add_form_id,
    submit_date: formattedDate,
  }).then((data) => {
    if (data === 1) {
      ElMessage.success("提交成功！");
      checkDialogVisible.value = false;
    }
  });
};

const handleSwitch = () => {
  switchAB.value = !switchAB.value;
};

// 下载
const downloadDetail = async () => {
  // console.log("下载");
  showTargetPage.value = true;
  await nextTick();
  window.print();
  setTimeout(() => {
    showTargetPage.value = false;
  }, 1000);
};
</script>

<template>
  <div class="card">
    <div v-show="!showTargetPage && switchAB">
      <el-card class="box-card">
        <h1 style="text-align: center">
          环境空气和废气 电感耦合等离子体质谱法分析原始记录（A面）
        </h1>
        <div>SXLPHJ/JL/CX-22-75</div>
        <table class="table">
          <tr>
            <td colspan="2" style="width: 10%">任务编号</td>
            <td colspan="3" style="width: 15%">
              <el-input
                v-model="waterForm.task_name"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2" style="width: 10%">采样日期</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.sampling_time"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2" style="width: 10%">分析日期</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.anal_time"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2" style="width: 10%">样品类别</td>
            <td colspan="3" style="width: 15%">
              <el-input
                v-model="waterForm.category_id"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <!-- 第二行 -->
          <tr style="background-color: #f2f2f2">
            <td colspan="2">分析方法</td>
            <td colspan="8">
              <el-input
                v-model="waterForm.method"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">环境条件</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.temperature"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              >
                <template #append>
                  <span style="background-color: transparent; color: black">
                    ℃
                  </span>
                </template>
              </el-input>
            </td>
            <td colspan="2">环境湿度</td>
            <td colspan="4">
              <el-input
                v-model="waterForm.humidity"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              >
                <template #append>
                  <span style="background-color: transparent; color: black">
                    %RH
                  </span>
                </template>
              </el-input>
            </td>
          </tr>
          <!-- 仪器 -->
          <MyDevice :water-form="waterForm" :colspan="8" />
          <tr style="background-color: #f2f2f2">
            <td colspan="2">仪器条件</td>
            <td colspan="5">
              <el-input
                v-model="waterForm.yqtj"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="3">计算公式</td>
            <td colspan="5">
              <el-input
                v-model="waterForm.js_formula"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">基准含氧量φ(O₂)</td>
            <td colspan="4">
              <el-input
                v-model="waterForm.jzyhl"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="2">前处理方法</td>
            <td colspan="8">
              <el-input
                v-model="waterForm.process"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">内标响应范围%</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.nbxyfw"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">内标元素</td>
            <td colspan="4">
              <el-input
                v-model="waterForm.nbys"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr style="text-align: center; background-color: #f2f2f2">
            <td colspan="2">备注</td>
            <td colspan="19">
              <el-input
                v-model="waterForm.notes"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width: 100%; height: 500px" />
      </el-card>
    </div>
    <div v-show="showTargetPage">
      <indexPdf
        :waterForm="waterForm"
        :tableHeaders="tableHeaders"
        :tabler="tabler"
      />
    </div>
    <div v-show="!switchAB">
      <capacity-b :water-form="waterForm" />
    </div>

    <!--    底部公共按钮 (复制粘贴)-->
    <div v-show="!showTargetPage">
      <Index
        :water-form="waterForm"
        :handle-add-water-ph="handleAddWaterPh"
        :download-detail="downloadDetail"
        :check-time="checkTime"
        :switch="true"
        :switch-a-b="switchAB"
        :handle-switch="handleSwitch"
        :get-water-capacity="getWaterCapacity"
        :switch-add="switchAdd"
      />
    </div>
  </div>
</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
